package com.william.lifetraxer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class Register extends BasicActivity {

	private EditText username = null;
	private EditText password = null;
	private EditText repeatPassword = null;
	private EditText birthday = null;
	private EditText phone = null;
	private EditText email = null;
	private Button register = null;
	private Button cancel = null;
	private RadioButton isMale = null;
	private RadioButton isFemale = null;

	private final int REGISTER_SUCCESS = 3;
	private final int REGISTER_FAILED = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initViews();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			showOnCancelDialog();
		}
		return false;
	}

	private void initViews() {
		username = (EditText) findViewById(R.id.register_edittext_username);
		password = (EditText) findViewById(R.id.register_edittext_password);
		repeatPassword = (EditText) findViewById(R.id.register_edittext_repeat_password);
		birthday = (EditText) findViewById(R.id.register_edittext_birthday);
		phone = (EditText) findViewById(R.id.register_edittext_phone);
		email = (EditText) findViewById(R.id.register_edittext_email);
		isMale = (RadioButton) findViewById(R.id.register_radiobutton_male);
		isFemale = (RadioButton) findViewById(R.id.register_radiobutton_female);

		register = (Button) findViewById(R.id.register_button_register);
		register.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				startRegister();
			}

		});
		cancel = (Button) findViewById(R.id.register_button_cancel);
		cancel.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showOnCancelDialog();
			}

		});
	}

	private void showOnCancelDialog() {
		String title = this.getResources().getString(
				R.string.register_dialog_on_cancel_title_text);
		String content = this.getResources().getString(
				R.string.register_dialog_on_cancel_content_text);
		String yes = this.getResources().getString(
				R.string.register_dialog_on_cancel_yes_text);
		String no = this.getResources().getString(
				R.string.register_dialog_on_cancel_no_text);
		int icon = R.drawable.dialog_icon;
		DialogInterface.OnClickListener posListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Register.this.finish();
			}

		};
		DialogInterface.OnClickListener nagListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}

		};
		this.createSimpleDialog(icon, title, content, yes, posListener, no,
				nagListener).show();
	}

	private void startRegister() {
		String usernameStr = username.getText().toString();
		String passwordStr = password.getText().toString();
		String repeatPasswordStr = repeatPassword.getText().toString();
		String birthdayStr = birthday.getText().toString();
		String phoneStr = phone.getText().toString();
		String emailStr = email.getText().toString();
		boolean isMaleBool = isMale.isChecked();
		boolean isFemaleBool = isFemale.isChecked();
		String gender = isMaleBool ? "1" : (isFemaleBool ? "0" : "2");

		String msg = null;

		if (!"".equals(usernameStr) && usernameStr != null
				&& !"".equals(passwordStr) && passwordStr != null) {
			
				if (!isUsernameOk(usernameStr)) {
					msg = this.getResources().getString(
							R.string.register_toast_username_error_text);
					username.setText("");
					showMessageToast(msg, 3000);
					return;
				}
			
				if (!isPasswordOk(passwordStr)) {
					msg = this.getResources().getString(
							R.string.register_toast_password_error_text);
					password.setText("");
					repeatPassword.setText("");
					showMessageToast(msg, 3000);
					return;
				}
			
				if (!isBirthdayOk(birthdayStr)) {
					msg = this.getResources().getString(
							R.string.register_toast_birthday_error_text);
					birthday.setText("");
					showMessageToast(msg, 3000);
					return;
				}
			
				if (!isEmailOk(emailStr)) {
					msg = this.getResources().getString(
							R.string.register_toast_email_error_text);
					email.setText("");
					showMessageToast(msg, 3000);
					return;
				}
			
				if (!passwordStr.equals(repeatPasswordStr)) {
					msg = this.getResources().getString(
							R.string.register_toast_repeat_password_error_text);
					repeatPassword.setText("");
					showMessageToast(msg, 3000);
					return;
				}
			
				Intent intent = new Intent(this, DuringRegister.class);

				Bundle extra = new Bundle();
				extra.putString("username", usernameStr);
				extra.putString("password", passwordStr);
				extra.putString("birthday", birthdayStr);
				extra.putString("phone", phoneStr);
				extra.putString("email", emailStr);
				extra.putString("gender", gender);

				intent.putExtra("fromRegister", extra);

				startActivityForResult(intent, 1);
				
		} else {
			msg = this.getResources().getString(
					R.string.register_toast_essential_null_text);
			showMessageToast(msg, 3000);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case REGISTER_SUCCESS:
			Intent i = new Intent();
			Bundle b = new Bundle();
			b.putString("username", username.getText().toString());
			b.putString("password", password.getText().toString());
			i.putExtra("fromRegister", b);
			this.setResult(REGISTER_SUCCESS, i);
			this.finish();
			break;
		case REGISTER_FAILED:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean isUsernameOk(String username) {
		Pattern pattern = Pattern.compile("[a-zA-Z]*");
		Matcher matcher = pattern.matcher(username);
		boolean result = matcher.matches();
		return result;
	}

	private boolean isPasswordOk(String password) {
		Pattern pattern = Pattern.compile("[0-9a-zA-Z]*");
		Matcher matcher = pattern.matcher(password);
		boolean result = matcher.matches();
		return result;
	}

	private boolean isBirthdayOk(String birthday) {
		if ("".equals(birthday) || birthday == null) {
			return true;
		}

		int[] regularYear = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		int[] leapYear = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		boolean result = false;

		Pattern pattern = Pattern.compile("[-0]+");
		String[] strs = pattern.split(birthday);

		if (strs.length != 3) {
			return false;
		}

		int year = Integer.parseInt(strs[0]);
		int month = Integer.parseInt(strs[1]);
		int day = Integer.parseInt(strs[2]);
		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
			result = ((day > 0) && (leapYear[month] >= day));
		} else {
			result = ((day > 0) && (regularYear[month] >= day));
		}

		return result;
	}

	private boolean isEmailOk(String email) {
		if ("".equals(email) || email == null) {
			return true;
		}
		Pattern pattern = Pattern.compile("[0-9a-zA-Z]*@[0-9a-zA-Z]*[.]com");
		Matcher matcher = pattern.matcher(email);
		boolean result = matcher.matches();
		return result;
	}
}
